package net.chenlin.dp.ids.client.manager.impl;

import net.chenlin.dp.ids.client.config.PassportClientConfig;
import net.chenlin.dp.ids.client.manager.AuthCheckManager;
import net.chenlin.dp.ids.client.util.HttpUtil;
import net.chenlin.dp.ids.common.base.BaseResult;
import net.chenlin.dp.ids.common.constant.IdsConst;
import net.chenlin.dp.ids.common.entity.SessionData;
import net.chenlin.dp.ids.common.entity.TicketValidateResultDTO;
import net.chenlin.dp.ids.common.util.CommonUtil;
import net.chenlin.dp.ids.common.util.CookieUtil;
import net.chenlin.dp.ids.common.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 校验manager
 * @author zcl<yczclcn@163.com>
 */
@Component("authCheckManager")
public class AuthCheckManagerImpl implements AuthCheckManager {

    @Autowired
    private PassportClientConfig clientConfig;

    /**
     * 刷新session：web
     * @param request
     */
    @Override
    public void refreshWebSession(HttpServletRequest request) {
        String sessionId = CookieUtil.getVal(request, clientConfig.getAuthIdCookieName());
        Map<String, Object> param = clientParamMap(IdsConst.LOGIN_TYPE_WEB, sessionId);
        HttpUtil.doPost(clientConfig.getServAuthRefreshUrl(), param);
    }

    /**
     * 获取SessionData：web
     * @param request
     * @return
     */
    @Override
    public SessionData checkWebSession(HttpServletRequest request) {
        String sessionId = CookieUtil.getVal(request, clientConfig.getAuthIdCookieName());
        return checkClientSession(sessionId, IdsConst.LOGIN_TYPE_WEB);
    }

    /**
     * 校验ticket合法性
     * @param ticket
     * @return
     */
    @Override
    public TicketValidateResultDTO validateTicket(String ticket) {
        Map<String, Object> param = new HashMap<>(3);
        param.put("appCode", clientConfig.getAppCode());
        param.put("loginType", getClientType());
        param.put("ticket", ticket);
        String json = HttpUtil.doPost(clientConfig.getServTicketValidUrl(), param);
        if (CommonUtil.strIsNotEmpty(json)) {
            BaseResult baseResult = JsonUtil.toObj(json, BaseResult.class);
            if (baseResult != null && baseResult.success()) {
                return JsonUtil.toObj(baseResult.getRespData().toString(), TicketValidateResultDTO.class);
            }
        }
        return null;
    }

    /**
     * 获取SessionData：app
     * @param request
     * @return
     */
    @Override
    public SessionData checkAppSession(HttpServletRequest request) {
        String sessionId = getAuthId(request);
        return checkClientSession(sessionId, IdsConst.LOGIN_TYPE_APP);
    }

    /**
     * app登出
     * @param request
     */
    @Override
    public void removeAppSession(HttpServletRequest request) {
        Map<String, Object> param = clientParamMap(IdsConst.LOGIN_TYPE_APP, getAuthId(request));
        HttpUtil.doPost(clientConfig.getServAuthRemoveUrl(), param);
    }

    /**
     * 构造客户端请求参数map
     * @param loginType
     * @param sessionId
     * @return
     */
    private Map<String, Object> clientParamMap(Integer loginType, String sessionId) {
        Map<String, Object> param = new HashMap<>(3);
        param.put("appCode", clientConfig.getAppCode());
        param.put("loginType", loginType);
        param.put("sessionId", sessionId);
        return param;
    }

    /**
     * 获取SessionData
     * @param sessionId
     * @param loginType
     * @return
     */
    @Override
    public SessionData checkClientSession(String sessionId, Integer loginType) {
        if (CommonUtil.strIsNotEmpty(sessionId)) {
            Map<String, Object> param = clientParamMap(loginType, sessionId);
            String json = HttpUtil.doPost(clientConfig.getServAuthStatusUrl(), param);
            if (CommonUtil.strIsNotEmpty(json)) {
                BaseResult baseResult = JsonUtil.toObj(json, BaseResult.class);
                if (baseResult != null && baseResult.success()) {
                    return JsonUtil.toObj(baseResult.getRespData().toString(), SessionData.class);
                }
            }
        }
        return null;
    }

    /**
     * 从请求头或者参数中获取authId
     * @param request
     * @return
     */
    private String getAuthId(HttpServletRequest request) {
        String authId = request.getHeader(clientConfig.getAuthIdCookieName());
        if (CommonUtil.strIsEmpty(authId)) {
            authId = request.getParameter(clientConfig.getAuthIdCookieName());
        }
        return authId;
    }

    /**
     * 获取客户端类型标识，1：web端，2：服务端
     * @return
     */
    private Integer getClientType() {
        return "APP".equals(clientConfig.getClientType()) ? IdsConst.LOGIN_TYPE_APP : IdsConst.LOGIN_TYPE_WEB;
    }

}
